#! /usr/bin/env node
//(6)正确使用es6语法
//(5)正确使用commonjs规范
//(1)正确使用fs
const fs = require("fs");
//(4)正确使用path
const { join } = require("path");
//(2)正确使用http
const http = require("http");
//(8)正确使用open包
const open = require("open");
const { program } = require('commander');
program.version('0.0.1')
    .option('-p, --port <item>', 'this is port')
    // (10)正确使用process解析命令行参数
    .parse(process.argv);
const options = program.opts();
//端口号
//(11)考虑命令行工具参数的容错性
let wjj = "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimage.tupian114.com%2F20140417%2F13325010.png.thumb.jpg"
let wj = 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic.51yuansu.com%2Fpic2%2Fcover%2F00%2F40%2F20%2F581314139ee39_610.jpg&refer=http%3A%2F%2Fpic.51yuansu.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg'
const myHtml = fs.readFileSync("./publish/index.html","utf-8");
function getList(requrl){
    console.log(requrl);
    if(requrl.split(".")[1]){
        var fileData = fs.readFileSync(process.cwd()+requrl,"utf-8")
    }else{
        var fileArr = fs.readdirSync(process.cwd()+requrl);
    }
    return userHtml = myHtml.replace("<!-- 666 -->",requrl.split(".")[1]? fileData : fileArr.map(item=>`<li><img alt="" src=${item.split(".")[1]?wj:wjj} /> <a href="${requrl==="/"?requrl:requrl+"/"}${item}" >${item}</a></li>`).join(""))
}
const userPort = options.port>0&&options.port<65535 ? options.port : 8000;
http.createServer((req, res) => {
    if(req.url==="/favicon.ico"){return}
    res.end(getList(req.url))
    //(9)正确使用解析--port参数
    console.log(req.url);
}).listen(userPort, async () => {
    //(7)实现自动打开浏览器
    await open(`http://localhost:${userPort}`);
})